package com.ljy.system.marvel_sys.common.shiro.web;

import com.ljy.system.marvel_sys.common.shiro.cache.ShiroCache;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.subject.Subject;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @version 1.0.0
 * @ClassName: LogOutFilter
 * @Description: shiro退出过滤器
 * @author: LiJunYi
 * @create: 2020/4/13 9:10
 */
public class LogoutFilter extends org.apache.shiro.web.filter.authc.LogoutFilter{

    /**
     * 退出后重定向的地址
     */
    private String loginUrl;

    // 缓存名称
    private String cacheName;

    /** 缓存*/
    private ShiroCache<Object,Object> cache;

    public String getLoginUrl() {
        return loginUrl;
    }

    public void setLoginUrl(String loginUrl) {
        this.loginUrl = loginUrl;
    }

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        try {
            Subject subject = getSubject(request, response);
            String redirectUrl = getRedirectUrl(request, response, subject);
            String username = (String) subject.getPrincipal();
            if (StringUtils.isNotEmpty(username)) {
                subject.getSession().getId();
                // 清理缓存
                cache.remove(username);
                // 清除该用户单登录控制缓存
                cache.remove("shiro:cache:kickout:"+username);
            }
            // 退出登录
            subject.logout();
            issueRedirect(request,response,redirectUrl);
        } catch (Exception ignored) {

        }
        return false;
    }

    /**
     * 退出跳转URL
     */
    @Override
    protected String getRedirectUrl(ServletRequest request, ServletResponse response, Subject subject) {
        String url = getLoginUrl();
        if (StringUtils.isNotEmpty(url)) {
            return url;
        }
        return super.getRedirectUrl(request, response, subject);
    }

    public void setCacheManeger(CacheManager cacheManager)
    {
        this.cache = (ShiroCache<Object, Object>) cacheManager.getCache("shiro-activeSessionCache");
    }
}
